package com.uflower.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import com.uflower.common.to.es.SkuEsModel;
import com.uflower.search.constant.Constant;
import com.uflower.search.service.SearchService;
import com.uflower.search.vo.SearchParams;
import com.uflower.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public SearchResult searchInEs(SearchParams params) {
        SearchResult searchResult = null;

        SearchRequest searchRequest = buildSearchRequest(params);
        try {
             SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            searchResult = buildSearchResult(search,params);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return searchResult;
    }

    private SearchResult buildSearchResult(SearchResponse search,SearchParams searchParams) {
        SearchResult searchResult = new SearchResult();
        SearchHits hits = search.getHits();
        //记录分页信息
        Long totalHits = hits.getTotalHits().value;
        Integer pageNum = searchParams.getPageNum();

        Integer totalPage =(int)(totalHits%pageNum==0?totalHits/pageNum:totalHits/pageNum+1);
        searchResult.setPageNum(pageNum);
        searchResult.setTotal(totalHits);
        searchResult.setTotalPage(totalPage);
        //封装esModel信息
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        if(totalHits > 0){
            List<SkuEsModel> products = new ArrayList<>();
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel sku = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if(!StringUtils.isEmpty(searchParams.getKeyword())){
                    for (Map.Entry<String, HighlightField> fieldEntry : hit.getHighlightFields().entrySet()) {
                        String key = fieldEntry.getKey();
                        String value = fieldEntry.getValue().getFragments()[0].toString();
                        if("skuTitle".equalsIgnoreCase(key)){
                            sku.setSkuTitle(value);
                        }
                    }
                }

                skuEsModels.add(sku);
            }
        }
        searchResult.setProducts(skuEsModels);
        //封装聚合信息
        //封装分类聚合信息
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = search.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            long catelogId = bucket.getKeyAsNumber().longValue();
            ParsedStringTerms catelog_name_agg = bucket.getAggregations().get("catelog_name_agg");
            String catelogName = catelog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatelogId(catelogId);
            catalogVo.setCatelogName(catelogName);
            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogVos(catalogVos);
        //封装属性聚合信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = search.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            Long attrId =  bucket.getKeyAsNumber().longValue();
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues  = new ArrayList<>();
            for (Terms.Bucket attr_value_aggBucket : attr_value_agg.getBuckets()) {
                attrValues.add(attr_value_aggBucket.getKeyAsString());
            }
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValues(attrValues);
            attrVos.add(attrVo);
        }
        searchResult.setAttrVos(attrVos);
        //封装品牌聚合信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = search.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            Long brandId = bucket.getKeyAsNumber().longValue();
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }
        searchResult.setBrandVos(brandVos);

        return searchResult;
    }

    /**
     *模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存），   排序，分页，高亮，     聚合分析
     */
    public SearchRequest buildSearchRequest(SearchParams params) {
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        String keyword = params.getKeyword();
        if(!StringUtils.isEmpty(keyword)){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", keyword)) ;
        }
        if(params.getCatalog3Id() != null){
            boolQueryBuilder.filter( QueryBuilders.termQuery("catelogId",params.getCatalog3Id()));
        }
        if(params.getBrandId() != null&&params.getBrandId().size()>0){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",params.getBrandId()));
        }


        boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",params.getHasStock() == 1));


        if(!StringUtils.isEmpty(params.getSkuPrice())){
            // _500 500_ 100_500
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = params.getSkuPrice().split("_");
            if(s.length == 2){
                rangeQuery.gte(s[0]);
                rangeQuery.lte(s[1]);
            }else if(params.getSkuPrice().startsWith("_")){
                rangeQuery.lte(s[0]);
            }else {
                rangeQuery.gte(s[0]);
            }
            boolQueryBuilder.filter(rangeQuery);
        }
        if(params.getAttrs()!= null&& params.getAttrs().size() > 0){
            // attr= 1_5寸：10寸

            for (String attrStr : params.getAttrs()) {
                BoolQueryBuilder nestedBoolQueryBuilder= QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                nestedBoolQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));


                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQueryBuilder, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }
        }
        builder.query(boolQueryBuilder);

        if(!StringUtils.isEmpty(params.getSort())){
            String[] s = params.getSort().split("_");
            builder.sort(s[0], s[1].equalsIgnoreCase("desc")?SortOrder.DESC:SortOrder.ASC);
        }

        builder.size(Constant.PAGESIZE);
        builder.from((params.getPageNum()-1)* Constant.PAGESIZE);

        if(!StringUtils.isEmpty(params.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            builder.highlighter(highlightBuilder);
        }
        //品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        builder.aggregation(brand_agg);
        //分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
        catalog_agg.field("catelogId").size(50);
        catalog_agg.subAggregation(AggregationBuilders.terms("catelog_name_agg").field("catelogName").size(1));
        builder.aggregation(catalog_agg);
        //属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");

        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(50);
        TermsAggregationBuilder attr_name_agg = AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1);
        TermsAggregationBuilder attr_value_agg = AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(1);
        attr_id_agg.subAggregation(attr_name_agg).subAggregation(attr_value_agg);
        attr_agg.subAggregation(attr_id_agg);

        builder.aggregation(attr_agg);

        SearchRequest searchRequest = new SearchRequest(new String[]{Constant.PRODUCT_INDEX}, builder);
        System.out.println(searchRequest.source());
        System.out.println(searchRequest);
        return searchRequest;
    }
}
